package com.leo.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class MappedByteBufferTest {
    public static void main(String[] args) throws IOException {

        RandomAccessFile raf = new RandomAccessFile("/Users/apple/Desktop/test/test.py", "rw");

        /**
         * 获取文件通道
         */
        FileChannel channel = raf.getChannel();

        // 也可以通过FileChannel的open来打开对应的fc
        //FileChannel fc = FileChannel.open(Paths.get("/usr/local/test.txt"), StandardOpenOption.WRITE);

        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());

        byte[] bytes = new byte[(int) channel.size()];
        buffer.get(bytes);
        System.out.println(new String(bytes));

        channel.close();
        raf.close();
    }
}
